package learning.socket5;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class Server {// has been finished
	public static void main(String[] args) {
		ServerSocket ss = null;
		Socket s = null;
		Map<String, Socket> map = new HashMap<String, Socket>();
		try {
			ss = new ServerSocket(5200);
			System.out.println("waiting...");// Sever Open
			while (true) {
				s = ss.accept();
				System.out.println("wellcom  "
						+ s.getInetAddress().getHostName());
				new Sent_msg(map, s).start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

class Sent_msg extends Thread {
	Map<String, Socket> map;
	Socket s;

	public Sent_msg(Map<String, Socket> map, Socket s) {
		super();
		this.map = map;
		this.s = s;
	}

	@Override
	public void run() {
		int count = 0;
		String name = "";
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					s.getInputStream()));
			while (true) {
				String receive = br.readLine().trim();
				if (count == 0) { // judge whether it is readed once
					name = receive;
					System.out.println(receive + " join us");
					count = -1;
					map.put(name, s);
				} else {
					for (Socket sk : map.values()) {// sent information to all
													// persons
						if (receive.charAt(0) == '@') {
							int ind = receive.indexOf(":");
							String str_name = receive.substring(1, ind);
							String str_msg = receive.substring(ind);
							BufferedWriter bw = new BufferedWriter(
									new OutputStreamWriter(map.get(str_name)
											.getOutputStream()));
							bw.write(name + str_msg);
							bw.newLine();
							bw.flush();

						} else {
							BufferedWriter bw = new BufferedWriter(
									new OutputStreamWriter(sk.getOutputStream()));
							bw.write(name + ":" + receive);
							bw.newLine();
							bw.flush();
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
